// pages/cart/cart.js
import { createStoreBindings } from 'mobx-miniprogram-bindings'
import { store } from '../../store/index'
import { showFeedbackToast } from '../../utils/show_toast'

Page({

  /**
   * 页面的初始数据
   */
  data: {
    allChecked: false,
    address: {},
    timer: null,
    seconds: 3
  },

  

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    if(typeof this.getTabBar === 'function' && this.getTabBar()) {
      this.getTabBar().setData({
        active: 2
      })
    }
    // 使用mobx
    this.storeBindings = createStoreBindings(this, {
      store,
      fields: ['bottomHeight', 'cart', 'totalPrice', 'checkedGoodsCount', 'cartCount', 'address', 'userInfo', 'addressStr'],
      actions: ['updateGoodsState', 'updateGoodsCount', 'deleteGoods', 'updateAllGoodsState', 'updateAddress', 'updateRedirectInfo', 'tokenHttp']
    })

    // 判断是否为全选状态
    wx.nextTick(() => {
      this.setData({
        address: this.data.address,
        allChecked: this.data.checkedGoodsCount === this.data.cartCount
      })
    })
  },

  // 监听商品点击勾选事件
  goodsStateChange(goods) {
    this.updateGoodsState(goods.detail)
    wx.nextTick(() => {
      // 判断是否要全选
      this.setData({
        allChecked: this.data.checkedGoodsCount === this.data.cartCount
      })
    })
  },
  // 改变商品数量
  goodsCountChange(goods) {
    this.updateGoodsCount(goods.detail)
  },
  // 删除商品
  goodsDelete(goods) {
    this.deleteGoods(goods.detail)
  },
  // 全选 / 反选商品
  goodsChecked(goods) {
    // 更新页面中的商品状态
    this.setData({
      cart: this.data.cart.map(x => {
        x.goods_state = goods.detail
        return x
      })
    })
    // 判断是否要全选
    this.setData({
      allChecked: goods.detail
    })
    // 更新mobx中商品状态
    this.updateAllGoodsState(goods.detail)
  },
  // 结算商品
  async settleGoods() {
    // 1.判断是否登录
    if(!this.data.userInfo.avatarUrl) {
      wx.showToast({
        title: '请登录后再结算！' + this.data.seconds + '秒后自动转跳到登录页',
        icon: 'none',
        mask: true,
      })
      this.setData({
        timer: setInterval(() => {
          this.setData({
            seconds: this.data.seconds - 1
          })
          wx.showToast({
            title: '请登录后再结算！' + this.data.seconds + '秒后自动转跳到登录页',
            icon: 'none',
            mask: true,
            success: () => {
              if (this.data.seconds <= 0) {
                clearInterval(this.data.timer)
                this.updateRedirectInfo({
                  openType: 'switchTab',
                  from: '/pages/cart/cart'
                })
                wx.switchTab({
                  url: '/pages/profile/profile',
                })
                return
              }
            }
          })
        }, 1000)
      })
    // 2.判断是否勾选商品 
    } else if(!this.data.checkedGoodsCount) {
      return showFeedbackToast('请先勾选商品!')
    // 3.判断是否填写收获地址
    } else if(!this.data.address.userName) { 
      return showFeedbackToast('请先选择收货地址!')
    }
    // 4.实现支付
    // 4.1创建订单
    const orderInfo = {
      order_price: 0.01,
      consignee_addr: this.data.addressStr,
      goods: this.data.cart.filter(x => x.goods_state).map(x => ({ goods_id: x.goods_id, goods_number: x.goods_count, goods_price: x.goods_price }))
    }

    // 4.2发起订单请求
    const { data: res } = await this.tokenHttp().post('/my/orders/create', orderInfo)
    console.log('创建订单请求', res)
    if(res.meta.status !== 200) return showFeedbackToast('创建订单失败！')
    // 4.2.1 得到服务器响应的订单号
    const order_number = res.message.order_number
    console.log('订单编号', orderNum)
    // 4.3 订单预支付
    // 4.3.1 发起请求获取订单支付信息
    const { data: res2 } = await this.tokenHttp().post('/my/orders/req_unifiedorder', { order_number })
    // 4.3.2 预付订单生成失败
    if(res2.meta.status !== 200) return showFeedbackToast('预付订单生成失败！')
    // 4.3.3 得到订单支付必要参数
    const payInfo = res.message.pay

    // 4.4 发起微信支付
    // 4.4.1 调用wx.requestPayment()
   const payRes = await wx.requestPayment(payInfo)
   console.log('调用微信支付接口 ', payRes)
    // 4.4.2 完成支付
    const { data: res3 } = await this.tokenHttp().post('/my/order/chkOrder', order_number)
    if(res3.meta.status !== 200) return showFeedbackToast('订单未支付！')
    showFeedbackToast('支付完成！', 'success')
  },

  // 获取收货地址
  chooseAddress() {
    console.log('点击')
    wx.chooseAddress({
      success: (result) => {
        console.log(result)
        this.setData({
          address: result
        })
        this.updateAddress(result)
      },
      fail: (err) => {
        if(err && err.errMsg === 'chooseAddress:fail auth deny') {
          this.setAuth()
        }
      }
    })
  },
  // 授权
  setAuth() {
    wx.openSetting({
      withSubscriptions: true,
      success: (res) => {
        console.log('授权', res)
        if(res.authSetting['scope.address']) console.log('授权成功！')
      }
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {
    // 解绑
    this.storeBindings.destroyStoreBindings()
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})
